package com.molyfun.parents.activity.coursecenter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.common.ShareDialogActivity;
import com.molyfun.parents.activity.myorder.OrderDetailActivity;
import com.molyfun.parents.activity.organization.OrganizationActivity;
import com.molyfun.parents.activity.store.fragment.ProductDetailContentFragment;
import com.molyfun.parents.activity.store.fragment.ProductDetailEvaluateFragment;
import com.molyfun.parents.activity.store.fragment.ProductDetailInfoFragment;
import com.molyfun.parents.fragment.BaseFragment;
import com.molyfun.parents.im.ConsultActivity;
import com.molyfun.parents.rest.bean.CreateCustomPlanResponse;
import com.molyfun.parents.rest.bean.CustomPlanlistResponse;
import com.molyfun.parents.rest.bean.ProductDetailInfoResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.ThreeTabBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.molyfun.parents.utils.Const.PRODUCT_ID;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:3/2/17.
 */

public class ProductDetailActivity extends BaseActivity implements View.OnClickListener, ThreeTabBar.ThreeBarClickListener, UIEventListener {

    @InjectView(R.id.base_title_left)
    ImageView mBack;
    @InjectView(R.id.product_title_bar)
    ThreeTabBar mProductTitleBar;
    //    @InjectView(R.id.tel)
//    ImageView mTel;
    @InjectView(R.id.base_title)
    TextView mBaseTitle;
    @InjectView(R.id.base_title_right)
    ImageView mRightBtn;
    @InjectView(R.id.kaitong)
    TextView mKaitong;
    @InjectView(R.id.bottom_layout)
    RelativeLayout mBottomLayout;
    @InjectView(R.id.product_share)
    ImageView mShare;
    @InjectView(R.id.product_price)
    TextView mProductPrice;
    @InjectView(R.id.product_count)
    TextView mProductCount;

    private List<BaseFragment> fragmentList = new ArrayList<>();
    ProductDetailContentFragment mProductDetailContentFragment;
    ProductDetailInfoFragment mProductDetailInfoFragment;
    ProductDetailEvaluateFragment mProductDetailEvaluateFragment;

    private String mProductId;
    private String mStudentId;
    private String mDepartName;
    private String mEmptyStr = "";
    private String mMsgId;
    private int mChatRowProduct;
    private int mCurrentTab;
    private ProductDetailInfoResponse.ProductDetailInfoBean mProductDetailBean;

    public static final void startActivity(Context context, String product_id) {
        Intent intent = new Intent();
        intent.setClass(context, ProductDetailActivity.class);
        intent.putExtra(PRODUCT_ID, product_id);
        context.startActivity(intent);
    }

    public static final void startActivity(Context context, String product_id, String mMsgId) {
        Intent intent = new Intent();
        intent.setClass(context, ProductDetailActivity.class);
        intent.putExtra(PRODUCT_ID, product_id);
        intent.putExtra(Const.MSG_ID, mMsgId);
        intent.putExtra(Const.DEPART_NAME, mMsgId);
        context.startActivity(intent);
    }

    public static final void startActivity(Context context, String product_id, String mStudentId, int str) {
        Intent intent = new Intent();
        intent.setClass(context, ProductDetailActivity.class);
        intent.putExtra(PRODUCT_ID, product_id);
        intent.putExtra(Const.STUDENT_ID, mStudentId);
        intent.putExtra(Const.CHATROWPRODUCT_CHAR, str);
        context.startActivity(intent);
    }

    @Override
    public void handleUIEvent(Message msg) {
        switch (msg.what) {
            case EventDispatcherEnum.UI_EVENT_ALIPAY_SUCCESS:
            case EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS:
                finish();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        ButterKnife.inject(this);
        getSupportActionBar().setTitle("");

        mProductId = getIntent().getStringExtra(PRODUCT_ID);
        mStudentId = getIntent().getStringExtra(Const.STUDENT_ID);
        mDepartName = getIntent().getStringExtra(Const.DEPART_NAME);
        mEmptyStr = getIntent().getStringExtra(Const.EMPTY_STR);
        mMsgId = getIntent().getStringExtra(Const.MSG_ID);
        mChatRowProduct = getIntent().getIntExtra(Const.CHATROWPRODUCT_CHAR, 0);
        mBack.setOnClickListener(this);
        mKaitong.setOnClickListener(this);
        mShare.setOnClickListener(this);
        mRightBtn.setOnClickListener(this);

//        mTel.setOnClickListener(this);
        if (!TextUtils.isEmpty(mProductId)) {
            getProductDetail(mProductId);
        }

        mProductTitleBar.setThreeBarClickListener(this);
        mProductTitleBar.initData("目录", "详情", "评价");

        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_ALIPAY_SUCCESS, this);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS, this);

    }

    private void initPage() {
        fragmentList.clear();
        fragmentList.add(mProductDetailContentFragment);
        fragmentList.add(mProductDetailInfoFragment);
        fragmentList.add(mProductDetailEvaluateFragment);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.content_main, fragmentList.get(0));
        fragmentTransaction.show(fragmentList.get(0));
        fragmentTransaction.commitAllowingStateLoss();
    }

    public BaseFragment getCurrentFragment() {
        return fragmentList.get(mCurrentTab);
    }

    private void changeFragment(int pageNum) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        getCurrentFragment().onPause();
        BaseFragment fragment = fragmentList.get(pageNum);

        if (fragment.isAdded()) {
            fragment.onResume();
        } else {
            fragmentTransaction.add(R.id.content_main, fragment);
        }

        if (pageNum == 0) {
            fragmentTransaction.show(fragmentList.get(0));
            fragmentTransaction.hide(fragmentList.get(1));
            fragmentTransaction.hide(fragmentList.get(2));
        } else if (pageNum == 1) {
            fragmentTransaction.show(fragmentList.get(1));
            fragmentTransaction.hide(fragmentList.get(0));
            fragmentTransaction.hide(fragmentList.get(2));
        } else {
            fragmentTransaction.show(fragmentList.get(2));
            fragmentTransaction.hide(fragmentList.get(0));
            fragmentTransaction.hide(fragmentList.get(1));
        }

        fragmentTransaction.commitAllowingStateLoss();

        mCurrentTab = pageNum;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.base_title_right:
                if(TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(this))){
                    OrganizationActivity.startActivity(this);
                }else{
                    createCustomplan();
                }
                break;
            case R.id.product_share:

                String shareUrl = "";

                switch (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) {
                    case PreferencesStorageUtil.ServerMode.OFFICAL:
                        shareUrl = "http://h5.helloparents.molyfun.com/#/subject/detail/" + mProductId;
                        break;
                    case PreferencesStorageUtil.ServerMode.PREPARE:
                        shareUrl = "http://h5.helloparentstest.molyfun.com/#/subject/detail/" + mProductId;
                        break;
                    case PreferencesStorageUtil.ServerMode.TEST:
                        shareUrl = "http://192.168.3.30:8081/helloparents-client/#/subject/detail/" + mProductId;
                        break;
                }

                ShareDialogActivity.sharePage(ProductDetailActivity.this, mProductDetailBean.getName(), mProductDetailBean.getIntroduce(), shareUrl);
                break;
//            case R.id.tel:
//
//                List<UserResponse.DepartBean> departBeenList = MFPApplication.getInstance().getUser().getDepartlist();
//                if (departBeenList != null && departBeenList.size() > 0) {
//                    UserResponse.DepartBean departBean = departBeenList.get(0);
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + departBean.getDeparttel()));
//                    ProductDetailActivity.this.startActivity(intent);
//                }
//                break;
            case R.id.kaitong:
                //TODO 立即开通之前做校验
                if(TextUtils.isEmpty(PreferencesStorageUtil.getStudentId(this))){
                    OrganizationActivity.startActivity(this);
                }else{
                    if (mProductDetailBean != null) {//&& mEmptyStr.equals(Const.EMPTY_STR) ||mEmptyStr.equals("")
                        OrderDetailActivity.startActivity(ProductDetailActivity.this, mProductDetailBean, mStudentId);
                    }
                }

                break;
        }
    }

    public void createCustomplan() {
        Call<CreateCustomPlanResponse> call = MFPApplication.getInstance().getRestClient().createCustomplan();
        call.enqueue(new Callback<CreateCustomPlanResponse>() {
            @Override
            public void onResponse(Call<CreateCustomPlanResponse> call, Response<CreateCustomPlanResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (response.body() != null && response.body().getData() != null) {
                            CustomPlanlistResponse.PlanListBean planListBean = response.body().getData();
                            String imgroupid = response.body().getData().getImgroupid();
//                            ChatActivity.startActivity(getContext(), response.body().getData(), response.body().getData().getImgroupid());
                            ConsultActivity.startActivity(ProductDetailActivity.this, planListBean, imgroupid);
                        }
                    } else {
                        toast(response.body().getMsg());
                    }
                }
            }

            @Override
            public void onFailure(Call<CreateCustomPlanResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });

    }

    @Override
    public void onThreeBarClick(int chooseTab) {
        switch (chooseTab) {
            case ThreeTabBar.ThreeTabChooseTab.BAR_ONE:
                changeFragment(0);
                break;
            case ThreeTabBar.ThreeTabChooseTab.BAR_TWO:
                changeFragment(1);
                break;
            case ThreeTabBar.ThreeTabChooseTab.BAR_THREE:
                changeFragment(2);
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_ALIPAY_SUCCESS, this);
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS, this);
    }


    private void getProductDetail(String productId) {
        showProgressDialog();
        Call<ProductDetailInfoResponse> call = MFPApplication.getInstance().getRestClient().getProductDetailInfo(productId);
        call.enqueue(new Callback<ProductDetailInfoResponse>() {
            @Override
            public void onResponse(Call<ProductDetailInfoResponse> call, Response<ProductDetailInfoResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200 && response.body().getData() != null) {
                        mProductDetailBean = response.body().getData();
                        mProductPrice.setText(mProductDetailBean.getPrice() + "");
                        mProductCount.setText(mProductDetailBean.getSellcount() + "人已报名");
                        mBaseTitle.setText(response.body().getData().getName());
                        mProductDetailInfoFragment = ProductDetailInfoFragment.newInstance(response.body().getData());
                        mProductDetailContentFragment = ProductDetailContentFragment.newInstance(response.body().getData());
                        mProductDetailEvaluateFragment = ProductDetailEvaluateFragment.newInstance(response.body().getData());
                        if (mProductDetailBean.isPurchasestatus()) {
                            mBottomLayout.setVisibility(View.GONE);
                        }
                        initPage();
                    } else {
                        toast(response.body().getMsg());
                    }
                } else {
                    toast("获取套餐详情失败");
                }
            }

            @Override
            public void onFailure(Call<ProductDetailInfoResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }
//
//    private void getProductDetail(String productId) {
//        showProgressDialog();
//        Call<ProductDetailResponse> call = MFPApplication.getInstance().getRestClient().getProductDetail(productId);
//        call.enqueue(new Callback<ProductDetailResponse>() {
//            @Override
//            public void onResponse(Call<ProductDetailResponse> call, Response<ProductDetailResponse> response) {
//                dismissProgressDialog();
//                if (response.body() != null) {
//                    if (response.body().getCode() == 200 && response.body().getData() != null) {
//                        mProductDetailBean = response.body().getData();
//                        mBaseTitle.setText(mProductDetailBean.getName());
//                        mProductDetailInfoFragment = ProductDetailInfoFragment.newInstance(response.body().getData());
//                        mProductDetailContentFragment = ProductDetailContentFragment.newInstance(response.body().getData());
//                        mProductDetailEvaluateFragment = ProductDetailEvaluateFragment.newInstance(response.body().getData());
//                        initPage();
//                    } else {
//                        toast(response.body().getMsg());
//                        finish();
//                    }
//                } else {
//                    toast("获取套餐详情失败");
//                    finish();
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ProductDetailResponse> call, Throwable t) {
//                dismissProgressDialog();
//            }
//        });
//    }

}
